package com.woniu.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.entity.Category;
import com.woniu.entity.CategoryCourse;
import com.woniu.entity.Course;
import com.woniu.dao.CourseDao;
import com.woniu.entity.PageResult;
import com.woniu.entity.vo.CourseVO;
import com.woniu.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.*;


/**
 * (Course)表服务实现类
 *
 * @author makejava
 * @since 2025-06-09 18:58:17
 */
@Service("courseService")
public
class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseDao courseDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Course queryById(Long id) {
        return this.courseDao.queryById(id);
    }

    /**
     * 通过课程ID获取课程信息
     * @param courseId
     * @return
     */
    @Override
    public CourseVO getCourseVOById(Integer courseId) {
        Integer uid = Integer.valueOf(StpUtil.getLoginId().toString());
        CourseVO courseVO = courseDao.getCourseVOById(courseId,uid);
        return courseVO;
    }

    /**
     * 递归查找选中分类id的的所有终子节点id,然后根据遍历出的最终分类id去查找课程id
     */
    @Override
    public List<Long> findAllLeafNodeIdsByCategoryId(Integer categoryId) {
        // 存储所有终子节点ID的列表
        List<Integer> leafNodeIds = new ArrayList<>();

        //存储所有课程id
        List<Long> courseIdList = new ArrayList<>();

        // 递归查找所有终子节点ID
        findLeafNodeIds(categoryId, leafNodeIds);

        for (Integer leafNodeId : leafNodeIds) {
            // 查找该终子节点ID对应的课程ID
            List<Long> courseIds = courseDao.queryCourseIdByCategoryId(leafNodeId);
            courseIdList.addAll(courseIds);
        }
        return courseIdList;
    }

    /**
     * 递归查找终子节点ID
     * @param categoryId 当前处理的分类ID
     * @param leafNodeIds 用于存储终子节点ID的列表
     */
    private void findLeafNodeIds(Integer categoryId, List<Integer> leafNodeIds) {
        // 获取当前分类的直接子分类
        List<Category> children = courseDao.findDirectSubCategories(categoryId);

        // 如果没有子分类，说明当前节点是终子节点
        if (children.isEmpty()) {
            // 将当前节点的ID添加到结果列表中
            leafNodeIds.add(categoryId);
            return;
        }

        // 递归处理每个子分类
        for (Category child : children) {
            findLeafNodeIds(child.getId(), leafNodeIds);
        }
    }

    /**
     * 根据课程id的集合查出所有课程信息封装到PageResult中
     */
    /**
     * 根据课程id的集合查出所有课程信息封装到PageResult中
     */
    public PageResult queryCourseByCourseIdList(Integer categoryId,Integer pageNum, Integer pageSize) {

        // 特殊处理：当categoryId=0时，查询所有课程
        if (categoryId == 0) {
            return findAllCourse(pageNum, pageSize);
        }
        // 获取所有叶子节点对应的课程ID列表
        List<Long> courseIdList = findAllLeafNodeIdsByCategoryId(categoryId);

        // 如果课程ID列表为空，返回空分页结果
        if (courseIdList.isEmpty()) {
            return new PageResult(pageNum, pageSize, 0L, 0, Collections.emptyList());
        }

        // 使用PageHelper进行分页
        PageHelper.startPage(pageNum, pageSize);

        // 批量查询课程信息
        List<Course> allCourse = courseDao.queryByIds(courseIdList);

        // 创建PageInfo对象获取分页信息
        PageInfo<Course> pageInfo = new PageInfo<>(allCourse);

        // 构建并返回PageResult对象
        return new PageResult(
                pageInfo.getPageNum(),
                pageInfo.getPageSize(),
                pageInfo.getTotal(),
                pageInfo.getPages(),
                pageInfo.getList()
        );
    }

    @Override
    public PageResult findAllCourse(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Course> allCourse = courseDao.findAllCourse();
        PageInfo<Course> pageInfo = new PageInfo<>(allCourse);
        List<Course> list = pageInfo.getList();
        PageResult pageResult = new PageResult(pageInfo.getPageNum(), pageInfo.getPageSize(),pageInfo.getTotal(), pageInfo.getPages(), list);
        return pageResult;
    }

    //根据浏览量排序
    @Override
    public List<Course> findAllCourseOrderByViewCount() {
        List<Course> allCourse = courseDao.findAllCourse();
        List<Course> list = allCourse.stream().sorted(new Comparator<Course>() {
            @Override
            public int compare(Course o1, Course o2) {
                return o2.getViewCount() - o1.getViewCount();
            }
        }).toList();
        return list;
    }
    @Override
    public List<Course> findAllCourseOrderByBuyCount() {
        List<Course> allCourse = courseDao.findAllCourse();
        List<Course> list = allCourse.stream().sorted(new Comparator<Course>() {
            @Override
            public int compare(Course o1, Course o2) {
                return o2.getBuyCount()- o1.getBuyCount();
            }
        }).toList();
        return list;
    }

    @Override
    public PageResult findByCondition(String title, String teacherName, Integer enable, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Course> courses = courseDao.findByCondition(title, teacherName, enable);
        PageInfo<Course> pageInfo = new PageInfo<>(courses);
        return new PageResult(
                pageInfo.getPageNum(),
                pageInfo.getPageSize(),
                pageInfo.getTotal(),
                pageInfo.getPages(),
                pageInfo.getList()
        );
    }
    /**
     * 推荐课程(学习人数前四)
     * @return
     */
    @Override
    public List<Course> getRecommendCourses() {
        return courseDao.getRecommendCourses();
    }

    /**
     * 最受欢迎的课程（观看人数前四）
     */
    @Override
    public List<Course> getPopularCourses() {
        return courseDao.getPopularCourses();
    }


    @Override
    public int insert(Course course) {
        return courseDao.insert(course);
    }

    @Transactional
    @Override
    public int update(Course course) {
        return courseDao.update(course);
    }

    @Transactional
    @Override
    public int deleteById(Long id) {
        // 先删除关联关系
         courseDao.deleteCourseCategories(id);

        // 再删除课程
        return courseDao.deleteById(id);
    }

    @Transactional
    @Override
    public void addCourseCategory(CategoryCourse categoryCourse) {
        courseDao.addCourseCategory(categoryCourse);
    }

    @Transactional
    @Override
    public void deleteCourseCategories(Integer courseId) {
        courseDao.deleteCourseCategories(courseId.longValue());
    }

    @Override
    public List<CategoryCourse> getCourseCategories(Integer courseId) {
        return courseDao.getCourseCategories(courseId);
    }

    @Override
    public CategoryCourse checkCategoryCourseExist(Integer courseId, Integer categoryId) {
        return courseDao.checkCategoryCourseExist(courseId.longValue(), categoryId);
    }

    @Override
    public List<Course> getFavoriteRankings() {
        return courseDao.getFavoriteRankings();
    }

    @Override
    public int countByTeacherId(Long teacherId) {
        return courseDao.countByTeacherId(teacherId);
    }

    @Override
    public PageResult getCourseByTeacherId(Long teacherId,Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Course> allCourse = courseDao.getCourseByTeacherId(teacherId);
        PageInfo<Course> pageInfo = new PageInfo<>(allCourse);
        List<Course> list = pageInfo.getList();
        PageResult pageResult = new PageResult(pageInfo.getPageNum(), pageInfo.getPageSize(),pageInfo.getTotal(), pageInfo.getPages(), list);
        return pageResult;
    }


}
